<?php

namespace common\components\image_beds\wbed;

use common\components\wtools\tools\ArrayHelper;
use common\Tools;
use GuzzleHttp\Client;
use yii\base\Component;

class Wbed extends Component
{
    public $baseUrl = '';
    public $uploadUri = '/api/user/file/upload-by-base64';
    public $token = '';
    public $key = '';

    protected function sign($form_params = [])
    {
        $form_params['timestamp'] = time();
        $form_params['nonce'] = $form_params['timestamp'].rand(100000000000, 400000000000);
        $p = $form_params;
        $p['key'] = $this->key;
        ksort($p);
        unset($p['sign']);
        $p_arr = [];
        foreach ($p as $k => $v) {
            $p_arr[] = $k."=".$v;
        }
        $p_str = ArrayHelper::arr2str($p_arr, '&');
        $form_params['sign'] = md5($p_str);
        return $form_params;
    }

    public function uploadByBase64($base64, $filename = null)
    {
        $config = [];
        if (YII_ENV_DEV) {
            $config['verify'] = false;
        }
        $client = new Client($config);
        $headers = [
            'authorization' => $this->token,
        ];
        $formParams = [
            'base64' => $base64,
        ];
        if ($filename) {
            $formParams['filename'] = $filename;
        }
        $form_params = $this->sign($formParams);
        $resp = $client->request("POST", $this->baseUrl . $this->uploadUri, [
            'headers' => $headers,
            'form_params' => $form_params,
        ]);
        $resp_cont = $resp->getBody()->getContents();
        $arr = Tools::isJson($resp_cont);
        if ($arr['code'] != 200) {
            throw new \Exception($resp_cont);
        }
        return $arr['data']['abUrl'];
    }
}